package com.example.blue;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import org.example.result.ZhenChanResult;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.PrimitiveIterator;
import java.util.concurrent.ConcurrentLinkedQueue;

import lombok.ToString;


public class TestResActivity extends AppCompatActivity implements DataProcessorManager.DataUpdateListener{
    public Integer predictLabel;
    public Integer predictScore;
    public double[] displayFea;
    public Integer pred1ctLabe1;
    public Integer RTScore;
    public Integer PScore;
    public Integer PTScore;
    public Integer PTTScoreRTDisFea;
    public double[] RTDisFea ;
    public double[] PDisFea ;
    public double[] PTDisFea  ;
    public double[] PTTDisFea ;


    private DataProcessorManager processorManager;
    private BluetoothService bluetoothService;
    private String deviceId;
    private  ProgressDialog progressDialog;

    private TextView duizhi_jiaosudu;
    private TextView dakai_jiaosudu;
    private TextView bihe_jiaosudu;
    private TextView duizhi_cishu;
    private TextView yuce_label;
    private TextView yuce_score;

    private String duizhi_jiaosudu_str;
    private String dakai_jiaosudu_str;
    private String bihe_jiaosudu_str;
    private String duizhi_cishu_str;
    private String yuce_label_str;
    private String yuce_score_str;

    private TextView zhenchan_lable;
    private TextView zhenchan_score;
    private TextView pingju_score;
    private TextView xiangxia_score;
    private TextView xiangnei_score;

    private TextView jingzhi_jizhiduan;
    private TextView jingzhi_jiaodu;
    private TextView jingzhi_pinglv;

    private TextView pingju_zhitiduan;
    private TextView pingju_jiaodu;
    private TextView pingju_pinglv;

    private TextView xiangxia_zhitiduan;
    private TextView xiangxia_jiaodu;
    private TextView xiangxia_pinglv;

    private TextView xiangnei_zhitiduan;
    private TextView xiangnei_jiaodu;
    private TextView xiangnei_pinglv;
    private TextView test_time;
    private TextView test_hand;

    private boolean isBound = false;
    private LinearLayout userform;
    private LinearLayout reportform;
    private Button confirmBtn;
    private Button cancelBtn;
    private EditText etName;
    private EditText etAge;
    private RadioGroup rgGender;
    private Integer handDir;
    private Boolean isSaveUserFile=true;

    private ConcurrentLinkedQueue<byte[]> dataQueue = new ConcurrentLinkedQueue<>();

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isBound = true;
            dataQueue  = bluetoothService.getDataQueue();
            System.out.println("testres----:" + dataQueue);

//            if(dataQueue.isEmpty()){
//                new AlertDialog.Builder(TestResActivity.this)
//                        .setTitle("提示")
//                        .setMessage("未收到数据，请重试")
//                        .setPositiveButton("确定", (dialog, which) -> {
//                            finish();
//                        })
//                        .show();
//            }else {
                processorManager = DataProcessorManager.getInstance(dataQueue);
                processorManager.setDataUpdateListener(TestResActivity.this);
                processorManager.startProcessing();
                processorManager.setProcessingFunction(ProcessingFunction.FinalRes);
                System.out.println("testres----:" + processorManager);

//                progressDialog = new ProgressDialog(TestResActivity.this);
//                progressDialog.setMessage("正在计算结果...");
//                progressDialog.setCancelable(false); // 点击返回是否可取消
//                progressDialog.show();

//            }
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_res);
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("测试结果报告");

        SharedPreferences sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        deviceId = sp.getString("deviceId", "");
        System.out.println(deviceId);
        if (deviceId == "" || deviceId.isEmpty()) {
            Toast.makeText(TestResActivity.this,"未获取到蓝牙MAC地址，请重新连接",Toast.LENGTH_SHORT).show();
        }
        handDir = sp.getInt("handDir",1);
        test_hand=findViewById(R.id.test_hand);
        if(handDir==1){
            test_hand.setText("测试手:左手");
        }else {
            test_hand.setText("测试手:右手");
        }
        test_time=findViewById(R.id.test_time);
        test_time.setText("测试时间:"+getCurrentTime());



        duizhi_jiaosudu=findViewById(R.id.duizhi_jiaosudu);
         dakai_jiaosudu=findViewById(R.id.dakai_jiaosudu);
          bihe_jiaosudu=findViewById(R.id.bihe_jiaosudu);
          duizhi_cishu=findViewById(R.id.duizhi_cishu);
          yuce_label=findViewById(R.id.yuce_label);
          yuce_score=findViewById(R.id.yuce_score);

          zhenchan_lable=findViewById(R.id.zhenchan_lable);
          zhenchan_score=findViewById(R.id.zhenchan_score);
          pingju_score=findViewById(R.id.pingju_score);
          xiangxia_score=findViewById(R.id.xiangxia_score);
          xiangnei_score=findViewById(R.id.xiangnei_score);

          jingzhi_jizhiduan=findViewById(R.id.jingzhi_jizhiduan);
          jingzhi_jiaodu=findViewById(R.id.jingzhi_jiaodu);
          jingzhi_pinglv=findViewById(R.id.jingzhi_pinglv);

          pingju_zhitiduan=findViewById(R.id.pingju_zhitiduan);
          pingju_jiaodu=findViewById(R.id.pingju_jiaodu);
          pingju_pinglv=findViewById(R.id.pingju_pinglv);

          xiangxia_zhitiduan=findViewById(R.id.xiangxia_zhitiduan);
          xiangxia_jiaodu=findViewById(R.id.xiangxia_jiaodu);
          xiangxia_pinglv=findViewById(R.id.xiangxia_pinglv);

          xiangnei_zhitiduan=findViewById(R.id.xiangnei_zhitiduan);
          xiangnei_jiaodu=findViewById(R.id.xiangnei_jiaodu);
          xiangnei_pinglv=findViewById(R.id.xiangnei_pinglv);

        predictLabel = sp.getInt("predictLabel", 0);
        predictScore = sp.getInt("predictScore", 0);
        String saved = sp.getString("displayFea", "");
        System.out.println("testres----:"+saved);
        if (!saved.isEmpty()) {
            String[] parts = saved.split(",");
            if (parts.length == 4) {
                duizhi_jiaosudu_str = String.format(Locale.US, "%.2e", Double.valueOf(parts[0])).toString();
                duizhi_jiaosudu.setText( duizhi_jiaosudu_str+ "rad/s");
                dakai_jiaosudu_str = String.format(Locale.US, "%.2e", Double.valueOf(parts[1])).toString();
                dakai_jiaosudu.setText(dakai_jiaosudu_str+ "rad/s");
                bihe_jiaosudu_str=String.format(Locale.US, "%.2e", Double.valueOf(parts[2])).toString();
                bihe_jiaosudu.setText(bihe_jiaosudu_str + "rad/s");
                duizhi_cishu_str=parts[3];
                duizhi_cishu.setText(duizhi_cishu_str + "次");
                yuce_label_str = predictLabel.toString();
                yuce_label.setText(utils.duizhiLabelChange(predictLabel));
                yuce_score_str=predictScore.toString();
                yuce_score.setText(predictScore.toString());
            } else {
                Toast.makeText(TestResActivity.this, "结果有错误，请重试", Toast.LENGTH_SHORT).show();
            }
        }
        userform=findViewById(R.id.user_form);
        confirmBtn =findViewById(R.id.btn_confirm);
        cancelBtn = findViewById(R.id.btn_cancel);
        etName = findViewById(R.id.et_name);
        etAge = findViewById(R.id.et_age);
        rgGender = findViewById(R.id.rg_gender);
        reportform=findViewById(R.id.report_form);
        reportform.setVisibility(View.GONE);
        confirmBtn.setOnClickListener(v -> {
            String name = etName.getText().toString().trim();
            String age = etAge.getText().toString().trim();
            int checkedId = rgGender.getCheckedRadioButtonId();
            String gender = "";
            if(checkedId == R.id.rb_male){
                gender="男";
            }
            if(checkedId == R.id.rb_female){
                gender="女";
            }
            // 在这里处理用户输入
            //Toast.makeText(this, "姓名:" + name + " 性别:" + gender + " 年龄:" + age, Toast.LENGTH_SHORT).show();
            if(name.isEmpty()){
                Toast.makeText(this, "姓名不能为空", Toast.LENGTH_SHORT).show();
            }else if(gender.isEmpty()){
                Toast.makeText(this, "性别不能为空", Toast.LENGTH_SHORT).show();

            }else if(age.isEmpty()){
                Toast.makeText(this, "年龄不能为空", Toast.LENGTH_SHORT).show();
            }else{

                saveUserFormFile(name,age,gender);
                userform.setVisibility(View.GONE);
                reportform.setVisibility(View.VISIBLE);
            }
        });
        cancelBtn.setOnClickListener(v -> {
            userform.setVisibility(View.GONE);
            reportform.setVisibility(View.VISIBLE);
        });

    }
    public static String getCurrentTime() {
        // 获取当前时间
        Date now = new Date();
        // 定义时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        // 格式化并返回
        return sdf.format(now);
    }
    public void saveUserFormFile(String name,String age,String sex){
        try {
            JSONObject obj = new JSONObject();
            obj.put("姓名", name);
            obj.put("性别", sex);
            obj.put("年龄", age);


            JSONObject duizhi_obj = new JSONObject();
            if(!duizhi_jiaosudu_str.isEmpty() && !dakai_jiaosudu_str.isEmpty() && !bihe_jiaosudu_str.isEmpty() && !duizhi_cishu_str.isEmpty() && predictLabel!=null && predictScore!=null) {
                duizhi_obj.put("对指角速度均方根", duizhi_jiaosudu_str);
                duizhi_obj.put("打开角速度均方根", dakai_jiaosudu_str);
                duizhi_obj.put("闭合角速度均方根", bihe_jiaosudu_str);
                duizhi_obj.put("完成对指次数", duizhi_cishu_str);
                duizhi_obj.put("预测的标签", predictLabel);
                duizhi_obj.put("预测评分", predictScore);
            }else{
                isSaveUserFile=false;
                Toast.makeText(this,"数据不全",Toast.LENGTH_SHORT).show();
            }
            JSONObject zhenchanobj = new JSONObject();
            if(pred1ctLabe1!=null && RTScore!=null && PScore!=null &&PTScore!=null && PTTScoreRTDisFea!=null) {
                zhenchanobj.put("疾病分类标签", pred1ctLabe1);
                zhenchanobj.put("静止性震颤评分", RTScore);
                zhenchanobj.put("姿势性震颤平举评分", PScore);
                zhenchanobj.put("双手置于胸前手心向下评分", PTScore);
                zhenchanobj.put("双手置于胸前手心向内评分", PTTScoreRTDisFea);
            }else{
                isSaveUserFile=false;
                Toast.makeText(this,"数据不全",Toast.LENGTH_SHORT).show();
            }
            JSONObject jingzhi_pbj = new JSONObject();
            if(RTDisFea!=null && RTDisFea.length==3) {
                jingzhi_pbj.put("最大震颤肢体段", RTDisFea[0]);
                jingzhi_pbj.put("最大震颤角度", RTDisFea[1]);
                jingzhi_pbj.put("平均震颤频率", RTDisFea[2]);
            }else{
                isSaveUserFile=false;
                Toast.makeText(this,"数据不全",Toast.LENGTH_SHORT).show();
            }
            JSONObject pingju_pbj = new JSONObject();
            if(PDisFea!=null && PDisFea.length==3) {
                pingju_pbj.put("最大震颤肢体段", PDisFea[0]);
                pingju_pbj.put("最大震颤角度", PDisFea[1]);
                pingju_pbj.put("平均震颤频率", PDisFea[2]);
            }else{
                isSaveUserFile=false;
                Toast.makeText(this,"数据不全",Toast.LENGTH_SHORT).show();
            }
            JSONObject xiangxia_pbj = new JSONObject();
            if(PTDisFea!=null && PTDisFea.length==3) {
                xiangxia_pbj.put("最大震颤肢体段", PTDisFea[0]);
                xiangxia_pbj.put("最大震颤角度", PTDisFea[1]);
                xiangxia_pbj.put("平均震颤频率", PTDisFea[2]);
            }else{
                isSaveUserFile=false;
                Toast.makeText(this,"数据不全",Toast.LENGTH_SHORT).show();
            }
            JSONObject xiangnei_pbj = new JSONObject();
            if(PTTDisFea!=null && PTTDisFea.length==3) {
                xiangnei_pbj.put("最大震颤肢体段", PTTDisFea[0]);
                xiangnei_pbj.put("最大震颤角度", PTTDisFea[1]);
                xiangnei_pbj.put("平均震颤频率", PTTDisFea[2]);
            }else{
                isSaveUserFile=false;
                Toast.makeText(this,"数据不全",Toast.LENGTH_SHORT).show();
            }
            JSONObject res_obj = new JSONObject();
            res_obj.put("用户信息",obj);
            res_obj.put("对指测试指标",duizhi_obj);
            res_obj.put("震颤测试指标",zhenchanobj);
            res_obj.put("静止性震颤测试指标",jingzhi_pbj);
            res_obj.put("平举测试指标",pingju_pbj);
            res_obj.put("双手置于胸前手心向下测试指标",xiangxia_pbj);
            res_obj.put("双手置于胸前手心向内测试指标",xiangnei_pbj);

            String jsonStr = res_obj.toString();
            if(isSaveUserFile==true) {
                utils.writeToFile(jsonStr, "user_info.txt");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this, BluetoothService.class);
        intent.putExtra("DEVICE_ADDRESS", deviceId); // 如果需要
        bindService(intent, connection, Context.BIND_AUTO_CREATE);

    }
    @Override
    public void onDataProcessed(ProcessedData data) {
        String processedValue = data.getValue();
        //  dataTextView.setText("收到数据: " + processedValue);
        String flag = data.getFlag();
        System.out.println("testRes-Flag:" + flag);
        if (flag.equals("zhenchanResult")) {
            ZhenChanResult zhenchanRes = data.getZhenChanResult();
            pred1ctLabe1=zhenchanRes.predictLabel;
            RTScore = zhenchanRes.RTScore;
            PScore =zhenchanRes.PScore;
            PTScore=zhenchanRes.PTScore;
            PTTScoreRTDisFea = zhenchanRes.PTTScore;
            RTDisFea = zhenchanRes.RTDisFea;
            PDisFea=zhenchanRes.PDisFea;
            PTDisFea = zhenchanRes.PTDisFea;
            PTTDisFea = zhenchanRes.PTTDisFea;

            zhenchan_lable.setText(utils.zhenchanLabelChange(pred1ctLabe1));
            zhenchan_score.setText(String.valueOf(RTScore));
            pingju_score.setText(String.valueOf(PScore));
            xiangxia_score.setText(String.valueOf(PTScore));
            xiangnei_score.setText(String.valueOf(PTTScoreRTDisFea));

            jingzhi_jizhiduan.setText(utils.resChange((int)RTDisFea[0]));
            jingzhi_jiaodu.setText(String.valueOf(RTDisFea[1])+" deg");
            jingzhi_pinglv.setText(String.valueOf(RTDisFea[2])+" HZ");

            pingju_zhitiduan.setText(utils.resChange((int)PDisFea[0]));
            pingju_jiaodu.setText(String.valueOf(PDisFea[1])+" deg");
            pingju_pinglv.setText(String.valueOf(PDisFea[2])+" HZ");

            xiangxia_zhitiduan.setText(utils.resChange((int)PTDisFea[0]));
            xiangxia_jiaodu.setText(String.valueOf(PTDisFea[1])+" deg");
            xiangxia_pinglv.setText(String.valueOf(PTDisFea[2])+" HZ");

            xiangnei_zhitiduan.setText(utils.resChange((int)PTTDisFea[0]));
            xiangnei_jiaodu.setText(String.valueOf(PTTDisFea[1])+" deg");
            xiangnei_pinglv.setText(String.valueOf(PTTDisFea[2])+" HZ");

//            progressDialog.dismiss();
        }
    }
    // 处理返回箭头点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}